package com.shop.apigateway.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;

/**
 * 限流
 *
 * @author denpeng
 * @create 2018-05-22 11:35
 **/
public class RateLimitFilter extends ZuulFilter {

  private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

  @Override
  public String filterType() {
    return PRE_TYPE;
  }

  @Override
  public int filterOrder() {
    return SERVLET_DETECTION_FILTER_ORDER - 1;//最高优先级
  }

  @Override
  public boolean shouldFilter() {
    return false;
  }

  @Override
  public Object run() throws ZuulException {
    if (!RATE_LIMITER.tryAcquire()) {
      throw new RuntimeException("请求失败");
    }
    return null;
  }
}
